package websocket.socket;

import java.util.HashMap;
import java.util.Map;

/**
 * websocket资源存储类，此类单例，不允许其它类实例化
 * 
 * @author zhc
 * 
 */
public class SocketContext {
	private static final SocketContext socketContext = new SocketContext();

	private static Map<Long, MyWebSocket> clients = new HashMap<Long, MyWebSocket>();// 存储所有客户端的socket对象

	private SocketContext() {

	}

	/**
	 * 获得当前类的实例对象
	 * 
	 * @return
	 */
	public static SocketContext getInstance() {
		return SocketContext.socketContext;
	}

	/**
	 * 添加一个客户的socket到map中去
	 * 
	 * @param id
	 *            用户ID
	 * @param socket
	 *            MyWebSocket对象
	 */
	public void addClient(Long id, MyWebSocket socket) {
		SocketContext.clients.put(id, socket);
	}

	/**
	 * 从map中移除一个socket
	 * 
	 * @param id
	 *            用户ID
	 * @return
	 */
	public MyWebSocket removeClient(Long id) {
		MyWebSocket socket = SocketContext.clients.remove(id);
		return socket;
	}

	/**
	 * 判断一个客户是否在clients中已经存在socket
	 * 
	 * @param id
	 *            用户ID
	 * @return
	 */
	public boolean isExist(Long id) {
		return SocketContext.clients.containsKey(id);
	}

	/**
	 * 通过用户ID来获得一个socket
	 * 
	 * @param id
	 *            用户ID
	 * @return
	 */
	public MyWebSocket getSocket(Long id) {
		return SocketContext.clients.get(id);
	}

}
